package com.daykw.douyin.task;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.entity.Record;
import org.nutz.dao.impl.NutDao;

import com.daykw.douyin.config.NutzDaoConfig;
import com.daykw.douyin.http.HttpBase;
import com.daykw.douyin.model.VideoAuth;
import com.daykw.douyin.model.VideoInfo;
import com.daykw.douyin.model.VideoTask;
import com.daykw.douyin.utils.SpringContextHolder;

public class VideoUidThread extends Thread {

	private static Logger logger = Logger.getLogger(VideoUidThread.class);
	private SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmss");

	@Override
	public void run() {

		try {
			NutDao dao = SpringContextHolder.getBean(NutzDaoConfig.class);

			List<VideoTask> tasks = dao.query(VideoTask.class,
					Cnd.where("uid_status", "=", 0).limit(1, 10).desc("uidby"));
			List<Record> cookies = dao.query("t_cookie", Cnd.wrap("WHERE status=1 "));
			HttpBase http = new HttpBase();
			Map<String, String> headers = new HashMap<String, String>();
			// String cookie = dao.fetch("t_cookie", Cnd.where("name", "=",
			// "大斌")).getString("cookie");

			for (VideoTask task : tasks) {

				int random = org.apache.commons.lang3.RandomUtils.nextInt(0, cookies.size());

				Record cookie = cookies.get(random);
				String c = cookie.getString("cookie");
				String cname = cookie.getString("name");
				VideoInfo video = dao.fetch(VideoInfo.class, Cnd.where("kw_id", "=", task.getKw_id()));

				Map<String, String> data = new HashMap<String, String>();
				data.put("promotionId", "");
				data.put("id", video.getDataid());
				data.put("awemeid", video.getKw_id());
				headers.put("Cookie", c);
				try {
					String html = http.post("https://dy.feigua.cn/Aweme/GetAwemeDetail", headers, data);
					if (html.equals("fail")) {
						dao.update(VideoTask.class, Chain.make("uid_status", 3),
								Cnd.where("kw_id", "=", video.getKw_id()));
						logger.error("抓取uid请求异常###########");
						continue;
					}
					Document doc = Jsoup.parse(html);

					Elements scripts = doc.getElementsByTag("script");
					String uid = null;
					for (Element s : scripts) {

						String script = s.toString();
						if (script.indexOf("GetComment?") > 0) {
							String[] sc = script.split("\r\n");

							for (String row : sc) {
								if (row.indexOf("GetComment?") > 0) {
									// var url = '/Aweme/GetComment?uid=63625792717' +
									// '&awemeId=6678156513263111432' + '&page=1';
									String r = row.substring(row.indexOf("uid=") + 4);
									r = r.substring(0, r.indexOf("'"));
									uid = r;
									break;
								}

							}

						}

					}
					Integer cmt_total = 0;
					String cmt_num = null;
					try {
						cmt_num = doc.select("div.content-list h5").first().ownText();
					} catch (Exception e) {
						logger.error("", e);
					}

					if (StringUtils.isNotEmpty(cmt_num)) {
						cmt_num = cmt_num.replace("(", "");
						cmt_num = cmt_num.replace(")", "");
						cmt_num = cmt_num.trim();
						try {
							cmt_total = Integer.parseInt(cmt_num);
						} catch (Exception e) {
							logger.error("", e);
						}

					}

					video.setUid(uid);
					String authname = doc.select("dl.one-info dd.name").text();
					video.setKw_auth_name(authname);
					String mid = doc.select("a.js-open-music-pop").attr("data-mid");
					String mname = doc.select("a.js-open-music-pop p.name").text();
					String muse = doc.select("a.js-open-music-pop p.use-number").text();
					video.setKw_music_name(mname);
					video.setKw_music_author(mname);
					video.setKw_music_id(mid);
					video.setKw_uid(uid);
					video.setKw_auth_url("https://www.iesdouyin.com/share/user/" + uid);

					if (StringUtils.isNotEmpty(muse)) {
						muse = muse.replaceAll("-", "");
						muse = muse.replaceAll("人使用", "");
						muse = muse.trim();
					}
					video.setKw_music_duration(muse);
					video.setUdate(Long.parseLong(fmt.format(new Date())));
					dao.updateIgnoreNull(video);

					if (StringUtils.isNotEmpty(uid)) {
						String cmt_url = "https://dy.feigua.cn/Aweme/GetComment?uid=" + uid + "&awemeId="
								+ video.getKw_id();
						dao.update(VideoTask.class,
								Chain.make("uid_status", 2).add("uid", uid).add("cmt_page", 1)
										.add("cmt_total", cmt_total).add("cmt_url", cmt_url),
								Cnd.where("kw_id", "=", video.getKw_id()));
						dao.update(VideoAuth.class, Chain
								.make("kw_user_url", "https://www.iesdouyin.com/share/user/" + uid).add("kw_uid", uid),
								Cnd.where("dataid", "=", video.getDataid()));

					} else {
						dao.update(VideoTask.class, Chain.make("uid_status", 2),
								Cnd.where("kw_id", "=", video.getKw_id()));
					}
					logger.info("##########" + task.getKw_id() + ",uid:" + uid + ",评论id抓完,cookie:" + cname);
					Thread.sleep(5000);
				} catch (Exception ee) {
					logger.error("", ee);
					dao.update(VideoTask.class, Chain.make("uid_status", 3), Cnd.where("kw_id", "=", video.getKw_id()));
				}

			}

		} catch (Exception e) {

			logger.error("", e);
		}

	}
}
